package com.yimicloud.common.freemarker;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Justin on 2015/9/7.
 */
public class FileHelper {
    public FileHelper() {
    }

    public static String getRelativePath(File baseDir, File file) {
        return baseDir.equals(file)?"":(baseDir.getParentFile() == null?file.getAbsolutePath().substring(baseDir.getAbsolutePath().length()):file.getAbsolutePath().substring(baseDir.getAbsolutePath().length() + 1));
    }

    public static String getRootPath(String rootDirEnd, File file) {
        String absolutePath = file.getAbsolutePath();
        return absolutePath.indexOf(rootDirEnd) > 0?absolutePath.substring(0, absolutePath.indexOf(rootDirEnd)):"";
    }

    public static void listFiles(File file, List collector) throws IOException {
        collector.add(file);
        if(!file.isHidden() && file.isDirectory() && !isIgnoreFile(file)) {
            File[] subFiles = file.listFiles();

            for(int i = 0; i < subFiles.length; ++i) {
                listFiles(subFiles[i], collector);
            }
        }

    }

    private static boolean isIgnoreFile(File file) {
        ArrayList ignoreList = new ArrayList();
        ignoreList.add(".svn");
        ignoreList.add("CVS");

        for(int i = 0; i < ignoreList.size(); ++i) {
            if(file.getName().equals(ignoreList.get(i))) {
                return true;
            }
        }

        return false;
    }

    public static void copyFile(File orig, File dest) {
        try {
            OutputStreamWriter e = new OutputStreamWriter(new FileOutputStream(dest), "utf-8");
            BufferedWriter bw = new BufferedWriter(e);
            InputStreamReader reader = new InputStreamReader(new FileInputStream(orig), "utf-8");
            BufferedReader br = new BufferedReader(reader);
            String content = "";

            for(String line = null; (line = br.readLine()) != null; content = content + line + "\n") {
                ;
            }

            bw.write(content);
            bw.flush();
            br.close();
            bw.close();
        } catch (FileNotFoundException var8) {
            var8.printStackTrace();
        } catch (IOException var9) {
            var9.printStackTrace();
        }

    }

    public static String getFileSuffix(File file) {
        String suffix = "";
        if(file.isFile()) {
            String fileName = file.getName();
            if(fileName.indexOf(".") > 0) {
                suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            }
        }

        return suffix;
    }
}
